package cn.magictodo.weblog.web.event.subscriber;

import cn.magictodo.weblog.web.event.AddIpEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static cn.magictodo.weblog.common.enums.RedisPrefixEnum.REDIS_IP_ID;

/**
 * 添加ip事件监听者
 * @author liu
 * @since 2024-03-25 23:14
 */
@Component
@Slf4j
public class AddIpSubscriber implements ApplicationListener<AddIpEvent> {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void onApplicationEvent(AddIpEvent event) {
        log.info("添加ip事件开始消费");
        Long ipId = event.getIpId();
        String s = REDIS_IP_ID.getPrefix() + ipId;
        //        查找redis是否有该值，如果有，则+1，如果没有，则添加，如果有则+1
        if (Boolean.TRUE.equals(redisTemplate.hasKey(s))) {
            redisTemplate.opsForValue().increment(s);
        } else {
            redisTemplate.opsForValue().set(s, 1,2, TimeUnit.DAYS);
        }
    }
}
